Week 4

Introduction

Today’s exercise exercise will focus on different techniques of clustering and classification. I will use data on housing in areas of Boston and mostly focus on the crime rate in the city. The data can be accessed through the R library MASS. The data contains area-level information on the characteristics of homes (size, value etc.), the demographic composition of the area as well as several variables related to environmental and infrastructural factors. More information on the data is available here and in the original study by Harrison & Rubinfeld (1978).

BTW, I decided to hide my code chunks by default in this course diary as they make reading a bit tedious. You should be able to get the codes by clicking the Code-button next to results.

Overview of the dataset

library(MASS)
library(tidyverse)
library(GGally)
library(corrplot)
data(Boston)
dim(Boston)
## [1] 506  14
str(Boston)
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08205   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00
hist(Boston$crim)

The data includes 14 variables from some 500 regions in Boston. All of them are numeric.My main varibale of interest, crime rate, seems highly skewed, with most of the areas having low rates of crime and a have expressing higher rates.

p.values.mat <-cor.mtest(Boston,
                         conf.level = .95)
cor.mat <- cor(Boston)
corrplot.mixed(cor.mat,
         lower.col='black',
               upper='color',
               tl.col='black',
               tl.cex=0.5,
               number.cex=0.5,
               p.mat=p.values.mat$p,
               sig.level=0.05)
Correlation plot

Correlation plot

For a graphical overview of data, I am using the correlation plot to make the plot to some extent readable (as compared to pairs or ggpairs. In the plot, I have crossed out all the correlations not significant at 95% confidence level. Accordingly, it seems that the variable chas is not significantly correlated with most of the variables (probably as it is binary). Most of the other variables are, and there seems to be relatively strong correlations, for instance rad tax 0.91, age and dis -0.75, nox indus 0.76. Most of the correlations seem moderate, between 0.3 and 0.6.Rad and tax for crime rate.

Linear Discriminant analysis

#Scale boston data

boston_scaled <- as.data.frame(scale(Boston))
summary(boston_scaled)
##       crim                 zn               indus              chas        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563   Min.   :-0.2723  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668   1st Qu.:-0.2723  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109   Median :-0.2723  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150   3rd Qu.:-0.2723  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202   Max.   : 3.6648  
##       nox                rm               age               dis         
##  Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331   Min.   :-1.2658  
##  1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366   1st Qu.:-0.8049  
##  Median :-0.1441   Median :-0.1084   Median : 0.3171   Median :-0.2790  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059   3rd Qu.: 0.6617  
##  Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164   Max.   : 3.9566  
##       rad               tax             ptratio            black        
##  Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047   Min.   :-3.9033  
##  1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876   1st Qu.: 0.2049  
##  Median :-0.5225   Median :-0.4642   Median : 0.2746   Median : 0.3808  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058   3rd Qu.: 0.4332  
##  Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372   Max.   : 0.4406  
##      lstat              medv        
##  Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 3.5453   Max.   : 2.9865

Tähän sössöä

#Save categories of crime rate
bins <- quantile(boston_scaled$crim)
#Create new crime variable
crime <- cut(boston_scaled$crim,
             breaks=bins,
             include.lowest=T,
             label=c(
               "low",
               "med_low",
               "med_high",
               "high"))
boston_scaled$crim <- NULL
boston_scaled$crime <- crime
#Divide data into test and training sets
n <- nrow(boston_scaled)
#Randomly sample 80% of the original rows
#These are used for training
ind <- sample(n, size=n*0.8)

#Train set
train <- boston_scaled[ind,]
#Test set
test <- boston_scaled[-ind,]

#Correct classes in the test set
correct <- test$crime

#Drop crime from test
test <- dplyr::select(test, -crime)
#LDA model
lda.fit <- 
  lda(crime~., data=train)

lda.fit
## Call:
## lda(crime ~ ., data = train)
## 
## Prior probabilities of groups:
##       low   med_low  med_high      high 
## 0.2450495 0.2623762 0.2425743 0.2500000 
## 
## Group means:
##                  zn      indus        chas        nox          rm        age
## low       1.0608843 -0.8978999 -0.11325431 -0.8914757  0.45663611 -0.9021716
## med_low  -0.0659521 -0.3676836 -0.01233188 -0.5943789 -0.12104669 -0.3709187
## med_high -0.3892353  0.1419212  0.16959035  0.3893871  0.08829714  0.3925050
## high     -0.4872402  1.0171306 -0.03844192  1.0559786 -0.40512004  0.8042585
##                 dis        rad        tax    ptratio      black      lstat
## low       0.9280665 -0.6930143 -0.7448216 -0.4674941  0.3790383 -0.7849373
## med_low   0.3793852 -0.5409032 -0.4871632 -0.1210827  0.3134269 -0.1572023
## med_high -0.3541221 -0.3818558 -0.2874823 -0.2467060  0.1472214  0.0348942
## high     -0.8677593  1.6379981  1.5139626  0.7806252 -0.8297808  0.8765519
##                 medv
## low       0.54744085
## med_low   0.02494892
## med_high  0.14654677
## high     -0.64184370
## 
## Coefficients of linear discriminants:
##                 LD1          LD2          LD3
## zn       0.10990805  0.766188216 -0.995049433
## indus   -0.05176076 -0.123477729  0.031533164
## chas    -0.07120442 -0.023889272  0.116907155
## nox      0.44937142 -0.771147396 -1.441766144
## rm      -0.09144206 -0.130455189 -0.221950157
## age      0.24460741 -0.225639801 -0.134655367
## dis     -0.09055557 -0.212480488  0.094620846
## rad      2.90499254  1.052508568  0.008616514
## tax      0.08009529 -0.117771732  0.704297122
## ptratio  0.14071054 -0.042921070 -0.388282334
## black   -0.15771751 -0.009575611  0.118640858
## lstat    0.19028501 -0.204419173  0.364995745
## medv     0.18928126 -0.296978809 -0.194957866
## 
## Proportion of trace:
##    LD1    LD2    LD3 
## 0.9442 0.0399 0.0159
# the function for lda biplot arrows
#(Stolen from Datacamp)
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

# target classes as numeric
classes <- as.numeric(train$crime)

# plot the lda results
plot(lda.fit, dimen = 2,
     col=classes,
     pch=classes)
lda.arrows(lda.fit, myscale = 2)

# predict classes with test data
lda.pred <- predict(lda.fit,
                    newdata = test)

# cross tabulate the results
table(correct = correct, 
      predicted = lda.pred$class)
##           predicted
## correct    low med_low med_high high
##   low       15      12        1    0
##   med_low    2      10        8    0
##   med_high   1       4       23    0
##   high       0       0        0   26
table(correct = correct, 
      predicted = lda.pred$class) %>%
  prop.table(2) %>% round(digits=2)
##           predicted
## correct     low med_low med_high high
##   low      0.83    0.46     0.03 0.00
##   med_low  0.11    0.38     0.25 0.00
##   med_high 0.06    0.15     0.72 0.00
##   high     0.00    0.00     0.00 1.00

K-means clustering

#Reload boston
data(Boston)
boston_scaled <-
  as.data.frame(scale(Boston))

#Calculate distances between observations
#I use Euclidean for no specific reason
#except that the km algorithm uses it
#by default

distances <- dist(boston_scaled)
summary(distances)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.1343  3.4625  4.8241  4.9111  6.1863 14.3970
#Identify correct number of clusters
#Use the WCSS for this purpose

k_max <- 15 #Arbitrary number

twcss <-
  sapply(1:k_max,
         function(k){
           kmeans(
             boston_scaled,k)$tot.withinss})
plot(x=1:k_max,y=twcss,type='l')

#2 seems appropriate
#Run k-means algorithm

km <- kmeans(boston_scaled,centers=2)

#Plot the data set in three parts
pairs(boston_scaled[
  c(1,5,6,7,8,12,13,14)], 
        col=km$cluster)

K-means + LDA

km2 <- kmeans(boston_scaled,centers=3)
boston_scaled$km_clust <- km2$cluster

#LDA model (rename to avoid confusion
#in the next step)
lda.fit2 <- 
  lda(km_clust~., data=boston_scaled)

lda.fit2
## Call:
## lda(km_clust ~ ., data = boston_scaled)
## 
## Prior probabilities of groups:
##         1         2         3 
## 0.4664032 0.3241107 0.2094862 
## 
## Group means:
##         crim         zn     indus        chas        nox          rm
## 1 -0.3760908 -0.3417123 -0.296848  0.01127561 -0.3345884 -0.09228038
## 2  0.8046456 -0.4872402  1.117990  0.01575144  1.1253988 -0.46443119
## 3 -0.4075892  1.5146367 -1.068814 -0.04947434 -0.9962503  0.92400834
##           age         dis        rad        tax     ptratio      black
## 1 -0.02966623  0.05695857 -0.5803944 -0.6030198 -0.08691245  0.2863040
## 2  0.79737580 -0.85425848  1.2219249  1.2954050  0.60580719 -0.6407268
## 3 -1.16762641  1.19486951 -0.5983266 -0.6616391 -0.74378342  0.3538816
##        lstat        medv
## 1 -0.1801190  0.03577844
## 2  0.8719904 -0.68418954
## 3 -0.9480974  0.97889973
## 
## Coefficients of linear discriminants:
##                 LD1         LD2
## crim    -0.03134296  0.14880455
## zn      -0.06381527  1.22350515
## indus    0.61086696  0.10402980
## chas     0.01953161 -0.03579238
## nox      1.00230143  0.70464917
## rm      -0.16285767  0.44390394
## age     -0.07220634 -0.59785382
## dis     -0.04270475  0.45498614
## rad      0.71987743  0.02882054
## tax      0.98285440  0.70663319
## ptratio  0.22527977  0.15514668
## black   -0.01693595 -0.03181845
## lstat    0.18274033  0.50122677
## medv    -0.02892966  0.64244841
## 
## Proportion of trace:
##    LD1    LD2 
## 0.8409 0.1591
classes <- 
  as.numeric(boston_scaled$km_clust)

# plot the lda results
plot(lda.fit2, dimen = 2,
     col=classes,
     pch=classes)
lda.arrows(lda.fit2, myscale = 2)

model_predictors <- 
  dplyr::select(train, -crime)

# check the dimensions
dim(model_predictors)
## [1] 404  13
dim(lda.fit$scaling)
## [1] 13  3
# matrix multiplication
matrix_product <- 
  as.matrix(model_predictors) %*% lda.fit$scaling

matrix_product <- as.data.frame(matrix_product)

library(plotly)

plot_ly(x = matrix_product$LD1,
        y = matrix_product$LD2,
        z = matrix_product$LD3,
        type= 'scatter3d',
        mode='markers',
        color=train$crime)
#let's fit still another k-means
data(Boston)
boston_scaled <- as.data.frame(scale(Boston))
train <- boston_scaled[ind,]
km3 <- kmeans(train, centers=2)

plot_ly(x = matrix_product$LD1,
        y = matrix_product$LD2,
        z = matrix_product$LD3,
        type= 'scatter3d',
        mode='markers',
        color=km3$cluster)

References

Harrison, D. & Rubinfeld, D.L. Hedonic housing prices and the demand for clean air. 1978. Journal of Environmental Economics and Management 5(1), 81-102.